import { sendRequest } from '@/http';

const baseUrl = '/admin/rbac';

/* 查询机构下的角色 */
export const queryPermissions = (params: any) =>
  sendRequest({
    url: `${baseUrl}/permissions`,
    method: 'get',
    params,
  });

/* 查询机构下的角色 */
export const queryRolesList = (params: any) =>
  sendRequest({
    url: `${baseUrl}/roles`,
    method: 'get',
    params,
  });

/* 添加角色 */
export const addRole = (data: any) =>
  sendRequest({
    url: `${baseUrl}/addRole`,
    method: 'post',
    data,
  });

/* 添加角色 */
export const editRole = (data: any) =>
  sendRequest({
    url: `${baseUrl}/editRole`,
    method: 'post',
    data,
  });

/* 启用角色 */
export const enableRole = (data: any) =>
  sendRequest({
    url: `${baseUrl}/enableRole`,
    method: 'post',
    data,
  });

/* 禁用角色 */
export const disableRole = (data: any) =>
  sendRequest({
    url: `${baseUrl}/disableRole`,
    method: 'post',
    data,
  });

/* 编辑角色的权限 */
export const addRolePermission = (data: any) =>
  sendRequest({
    url: `${baseUrl}/addRolePermission`,
    method: 'post',
    data,
  });

/* 编辑员工角色 */
export const addStaffRole = (data: any) =>
  sendRequest({
    url: `${baseUrl}/addStaffRole`,
    method: 'post',
    data,
  });

/* 删除员工角色 */
export const deleteRole = (roleId: string) =>
  sendRequest({
    url: `${baseUrl}/deleteRole`,
    method: 'post',
    data: { roleId },
  });

/* 查询平台用户 */
export const queryUsers = (params?: any) =>
  sendRequest({
    url: `/admin/account/queryStaffAccountList`,
    method: 'get',
    params,
  });

/* 查询用户拥有的权限 */
export const queryUserPermissions = (params: any) =>
  sendRequest({
    url: `${baseUrl}/userPermissions`,
    method: 'get',
    params,
  });

export const queryRolePermissions = (roleIds: string) =>
  sendRequest({
    url: '/admin/rbac/rolePermissions',
    method: 'get',
    params: { roleIds },
  });

const getBindIds = (data: any[]) => {
  const ids: string[] = [];

  data.forEach((e) => {
    ids.push(e.id);

    if (e.permissions && e.permissions.length > 0) {
      ids.push(...getBindIds(e.permissions));
    }
  });

  return ids;
};

export const queryRolePermissionsIds = (roleIds: string) => {
  return queryRolePermissions(roleIds).then((res) => {
    return getBindIds(res);
  });
};

/* 划分用户数据权限范围 */
export const setUserPermissionScope = (data: any) =>
  sendRequest({
    url: '/admin/rbac/setUserPermissionScope',
    method: 'post',
    data,
  });

/* 查询用户数据权限范围 */
export const queryUserPermissionScope = (userid: string) =>
  sendRequest({
    url: '/admin/rbac/queryUserPermissionScope',
    method: 'get',
    params: { userid },
  });
